# coding:utf-8

"""
Tencent is pleased to support the open source community by making HaboMalHunter available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in 
compliance with the License. You may obtain a copy of the License at

http://opensource.org/licenses/MIT

Unless required by applicable law or agreed to in writing, software distributed under the 
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
either express or implied. See the License for the specific language governing permissions 
and limitations under the License.
"""

import os
import sys
import json
import base64
from pyh import *


DICTIONARY_CONFIG = 'i18n.csv'
cn2enDict = {}

def ChangeELFLog2Html(sample_dir): 
    static_file  = "%s/%s.static" % (sample_dir,"output")
    dynamic_file = "%s/%s.xpcn" % (sample_dir,"output")
    html_file    = "%s/%s.html" % (sample_dir,"output")

    if os.path.isfile(static_file) :
        fStatic     = open(static_file, "r")
        staticJson  = json.loads(fStatic.read())
        fStatic.close()

    if os.path.isfile(dynamic_file):
        fDynamic    = open(dynamic_file, "r")
        dynamicJson = json.loads(fDynamic.read())
        fDynamic.close()

    if os.path.isfile(DICTIONARY_CONFIG):
        fDict = open(DICTIONARY_CONFIG, 'r')

        for line in fDict.readlines():
            item = line.split(',', 1)
            if len(item) == 2:
                key = item[0].decode('utf-8')
                cn2enDict[key] = item[1]

        fDict.close()



    page = PyH('Habo Analysis System')

    page.addStyleSnippet('head.css')
    page.addStyleSnippet('font-awesome.min.css')
    page.addStyleSnippet('common.css')
    page.addStyleSnippet('index.css')
    page.addStyleSnippet('detail.css')

    page << link(type="text/css", rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css")

    page << script('function f_show_sub_base(obj){\
                    $(obj).hide(); \
                    $("#subinfo").show();\
                    }\
                  ')

    #myImg = img(width='15', height='15', src='')


    myDivWrapper = div(cl='wrapper') 

    myDivContainer = div(cl='container extra-info', style='padding:10px 0') 

    myDivContainer << div(cl='clearfix') \
                   << div(cl='margin-top-2') \
                   << a()  \
                   << img( alt='VirusTotal', src='') 



    myDetailFrame = div(id='detail_frame')


    #BaseInfo
    myEnumContainer = div(cl='enum-container')

    myDivFrame = div(cl='frame', style='margin:20px 0') 
    myDivFrame << div(id='basic-info') \
               << div(cl='row') \
               << div(cl='span8 columns') 
    myTable = table(style='margin-bottom:8px;margin-left:8px;') 
    myTable << tbody()


    md5hash  = None
    filetype = None
    copyright = None
    productversion = None
    compiler = None

    if staticJson.has_key('BaseInfo'):

        if staticJson['BaseInfo'][0].has_key('MD5'):
            md5hash = staticJson['BaseInfo'][0]['MD5']

    if staticJson.has_key('BaseInfo'):

        if staticJson['BaseInfo'][0].has_key('FileType'):
            filetype = staticJson['BaseInfo'][0]['FileType']


    myTable << tr() \
                << td('MD5:') \
                << td('%s' % md5hash)

    myTable << tr() \
                << td('File type:') \
                << td('%s' % filetype)



    if staticJson.has_key('SubBaseInfo'):

        myTable <<  tr() 
        myTable << td('Sub-file information:', nowrap='nowrap', style='vertical-align:top') 


        myWordWrap  = td(style='word-wrap:break-word;word-break:break-all') 
        myWordWrap  << a('Detail', id='moreinfo', onclick='f_show_sub_base(this)', style='cursor:pointer')
        
            
        myTbody = tbody()

        for item in staticJson['SubBaseInfo']:

            subName = os.path.basename(item['Name'])
            subType = item['FileType']
            subMd5  = item['MD5']

            myEven  = tr(cl='even')
            myEven  << td('%s&nbsp;/&nbsp;%s&nbsp;/&nbsp;%s' % (subName, subMd5, subType))
 
            myTbody << myEven

        myWordWrap  << div(id='subinfo', style='display:none') \
                    << table(cl='dtable') \
                    << myTbody

        myTable << myWordWrap


    myEnumContainer << myDivFrame << myTable
    myDetailFrame << myEnumContainer


    #Dynamic Info------------------------------------

    if dynamicJson.has_key('Dynamic'):
        dynamicJson = dynamicJson['Dynamic']

    #Key behaviour
    if dynamicJson.has_key('KeyInfo') and len(dynamicJson['KeyInfo']) > 0:

        myDetailFrame << h5('Key behaviour') 
        myEnumContainer = div(cl='enum-container')
        myTable = table(cl='red dtable') 
        myTable << tbody()

        for key in dynamicJson['KeyInfo']:

            if key in cn2enDict:
                key_en = cn2enDict[key]
            else:
                key_en = key

            myTable << tr() \
                    << td('Behaviour:', cl='tdtitle') \
                    << td('%s' % key_en)

            myTd  =  td(style='word-wrap:break-word;word-break:break-all') 

            for item in dynamicJson['KeyInfo'][key]:

                myTd << p('%s' % item, title='%s' % item)

            myTable << tr() \
                    << td('Detail info:', width='1%', nowrap='nowrap', style='vertical-align:top') \
                    << myTd


        myEnumContainer  << myTable
        myDetailFrame << myEnumContainer

    #Process
    if dynamicJson.has_key('Process') and len(dynamicJson['Process']) > 0:

        myDetailFrame << h5('Process') 
        myEnumContainer = div(cl='enum-container')
        myTable = table(cl='dtable') 
        myTable << tbody()

        for key in dynamicJson['Process']:

            if key in cn2enDict:
                key_en = cn2enDict[key]
            else:
                key_en = key

            myTable << tr() \
                    << td('Behaviour:', cl='tdtitle') \
                    << td('%s' % key_en)

            myTd  =  td(style='word-wrap:break-word;word-break:break-all') 

            for item in dynamicJson['Process'][key]:

                myTd << p('%s' % item, title='%s' % item)

            myTable << tr() \
                    << td('Detail info:', width='1%', nowrap='nowrap', style='vertical-align:top') \
                    << myTd


        myEnumContainer  << myTable
        myDetailFrame << myEnumContainer



    #File
    if dynamicJson.has_key('File') and len(dynamicJson['File']) > 0:

        myDetailFrame << h5('File') 
        myEnumContainer = div(cl='enum-container')
        myTable = table(cl='dtable') 
        myTable << tbody()

        for key in dynamicJson['File']:

            if key in cn2enDict:
                key_en = cn2enDict[key]
            else:
                key_en = key

            myTable << tr() \
                    << td('Behaviour:', cl='tdtitle') \
                    << td('%s' % key_en)

            myTd  =  td(style='word-wrap:break-word;word-break:break-all') 

            for item in dynamicJson['File'][key]:

                myTd << p('%s' % item, title='%s' % item)

            myTable << tr() \
                    << td('Detail info:', width='1%', nowrap='nowrap', style='vertical-align:top') \
                    << myTd

        myEnumContainer  << myTable
        myDetailFrame << myEnumContainer


    #Network
    if dynamicJson.has_key('Net') and len(dynamicJson['Net']) > 0:

        myDetailFrame << h5('Network') 
        myEnumContainer = div(cl='enum-container')
        myTable = table(cl='dtable') 
        myTable << tbody()

        for key in dynamicJson['Net']:

            if key in cn2enDict:
                key_en = cn2enDict[key]
            else:
                key_en = key

            myTable << tr() \
                    << td('Behaviour:', cl='tdtitle') \
                    << td('%s' % key_en)

            myTd  =  td(style='word-wrap:break-word;word-break:break-all') 

            for item in dynamicJson['Net'][key]:

                myTd << p('%s' % item, title='%s' % item)

            myTable << tr() \
                    << td('Detail info:', width='1%', nowrap='nowrap', style='vertical-align:top') \
                    << myTd

        myEnumContainer  << myTable
        myDetailFrame << myEnumContainer

    #Registry
    if dynamicJson.has_key('Reg') and len(dynamicJson['Reg']) > 0:

        myDetailFrame << h5('Registry') 
        myEnumContainer = div(cl='enum-container')
        myTable = table(cl='dtable') 
        myTable << tbody()

        for key in dynamicJson['Reg']:

            if key in cn2enDict:
                key_en = cn2enDict[key]
            else:
                key_en = key

            myTable << tr() \
                    << td('Behaviour:', cl='tdtitle') \
                    << td('%s' % key_en)

            myTd  =  td(style='word-wrap:break-word;word-break:break-all') 

            for item in dynamicJson['Reg'][key]:

                myTd << p('%s' % item, title='%s' % item)

            myTable << tr() \
                    << td('Detail info:', width='1%', nowrap='nowrap', style='vertical-align:top') \
                    << myTd

        myEnumContainer  << myTable
        myDetailFrame << myEnumContainer

    #Hook
    if dynamicJson.has_key('Hook') and len(dynamicJson['Hook']) > 0:

        myDetailFrame << h5('Hook') 
        myEnumContainer = div(cl='enum-container')
        myTable = table(cl='dtable') 
        myTable << tbody()

        for key in dynamicJson['Hook']:

            if key in cn2enDict:
                key_en = cn2enDict[key]
            else:
                key_en = key

            myTable << tr() \
                    << td('Behaviour:', cl='tdtitle') \
                    << td('%s' % key_en)

            myTd  =  td(style='word-wrap:break-word;word-break:break-all') 

            for item in dynamicJson['Hook'][key]:

                myTd << p('%s' % item, title='%s' % item)

            myTable << tr() \
                    << td('Detail info:', width='1%', nowrap='nowrap', style='vertical-align:top') \
                    << myTd

        myEnumContainer  << myTable
        myDetailFrame << myEnumContainer

    #Other
    if dynamicJson.has_key('Other') and len(dynamicJson['Other']) > 0:

        myDetailFrame << h5('Other') 
        myEnumContainer = div(cl='enum-container')
        myTable = table(cl='dtable') 
        myTable << tbody()

        for key in dynamicJson['Other']:

            if key in cn2enDict:
                key_en = cn2enDict[key]
            else:
                key_en = key

            myTable << tr() \
                    << td('Behaviour:', cl='tdtitle') \
                    << td('%s' % key_en)

            myTd  =  td(style='word-wrap:break-word;word-break:break-all') 

            for item in dynamicJson['Other'][key]:

                myTd << p('%s' % item, title='%s' % item)

            myTable << tr() \
                    << td('Detail info:', width='1%', nowrap='nowrap', style='vertical-align:top') \
                    << myTd

        myEnumContainer  << myTable
        myDetailFrame << myEnumContainer

    myDivWrapper << myDivContainer << myDetailFrame
    myDivWrapper << div(cl='push')
    page << myDivWrapper

    page << div(cl='footer center') << div(u'Copyright © 1998 - 2016 Tencent.All Rights Reserved', style='width: 1000px; margin: 0 auto')

    page.printOut(html_file)



if __name__=="__main__":

    # arg1 = sample log directory
    # arg2 = log type(apk/pe)

    if sys.argv[2] == '-elf':
        ChangeELFLog2Html(sys.argv[1])